from django.shortcuts import render,redirect
from django.http import JsonResponse
from rest_framework.views import APIView
from data_app.models import Number
from django import forms
from django.db.models import Q
from django.core.paginator import Paginator
from utils.page import get_page
from django.conf import settings
from django.core.validators import RegexValidator
import re

# Create your views here.
def number_list(request):
    if request.method == 'GET':
        # 获取所有GET参数
        get_params = dict(request.GET)
        query_param = request.GET.get('query_param','')
        # 删除分页参数
        if 'page' in get_params:
            del get_params['page']
        str_params = ''
        if get_params:
            str_params = '&'.join(f'{k}={v[0]}' for k,v in get_params.items()) + '&'
        page_num = int(request.GET.get('page',1))
        queryset = Number.objects.filter(mobile__contains = query_param).order_by('-level')
        #创建一个分页器对象
        paginator = Paginator(queryset, int(settings.PAGE_SIZE))
        total_page = paginator.num_pages
        page_range = get_page(page_num,total_page,int(settings.PAGE_MIDDLE_DATA))
        #使用分页器对象的get_page方法获取指定页码的数据。
        page_data = paginator.get_page(page_num)
        return render(request,'number.html',{'queryset': page_data,'query':query_param,'page_range':page_range,'cur_num':page_num,'params':str_params})

class NumberModel(forms.ModelForm):
    #第一种验证方式
    # mobile = forms.CharField(label='手机号',validators=[
    #     RegexValidator(r'^1[3-9]\d{9}$', '手机号格式不正确'),
    # ])
    class Meta:
        model = Number
        fields = '__all__'
    #第二种验证方式
    def clean_mobile(self):
        mobile = self.cleaned_data['mobile']
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            raise forms.ValidationError('手机号格式不正确')
        b = Number.objects.filter(mobile=mobile).exclude(pk=self.instance.pk).exists()
        if b:
            raise forms.ValidationError('手机号已存在')
        return mobile
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name,field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}

class AddNumberView(APIView):
    def get(self, request):
        form = NumberModel()
        return render(request, 'number_add.html', {'form': form})
    def post(self, request):
        form = NumberModel(data = request.POST)
        if form.is_valid():
            form.save()
            return redirect('/number/list/')
        else:
            return render(request, 'number_add.html', {'form': form})
        
class EditNumberView(APIView):
    def get(self,request,pk):
        obj = Number.objects.get(pk=pk)
        form = NumberModel(instance=obj)
        return render(request,'number_edit.html',{'form': form})
    def post(self,request,pk):
        obj = Number.objects.get(pk=pk)
        form = NumberModel(request.POST,instance=obj)
        form.save()
        return redirect('/number/list/')
        
def delete_number(request):
    if request.method == 'GET':
        pk = request.GET.get('nid')
        Number.objects.filter(pk=pk).delete()
    return redirect('/number/list/')


def bar(request):
    if request.method == 'GET':
        return render(request,'paint.html')

import random

def d_bar(request):
    if request.method == 'GET':
        series = [[random.randint(100,500),random.randint(100,500),random.randint(100,500),random.randint(100,500),random.randint(100,500)]]
        return JsonResponse({'code':200,'data':series})

